package 算法;

public class BasicSearchDemo2 {
    public static void main(String[] args) {
                //二分查找/折半查找
                //核心：
                //每次排除一半的查找范围

                //需求：定义一个方法利用二分查找，查询某个元素在数组中的索引
                //数据如下：{7, 23, 79, 81, 103, 127, 131, 147}
        int []arr={7,23,79,81,103,127,131,147};
        System.out.println(binarySearch(arr,150));
    }
    public static int binarySearch(int []arr,int number){
        int left=0;
        int right=arr.length-1;
        int mid=(left+right)/2;
        while(left<=right)
        {
            if(arr[mid]<number){
                left=mid+1;
            }
            else if(arr[mid]>number){
                right=mid-1;
            }
            else if(arr[mid]==number){
                return mid;
            }
        }
        return 0;
    }
}
